package com.swpu.project.verification;


import com.swpu.project.model.entity.LoginUser;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("verf")
public class MyPremissionVerification
{
      private  static  final String MANAGE_MENU="MANAGE_MENU";


    public Boolean hasAuthorityFor(String...names)
     {
         LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
         List<String> premissions = principal.getPremissions();
         for (String name : names) {

            if(premissions.contains(name))
                return true;




         }




         return  false;
     }






    public   Boolean hasAnyAuthorityForBlock(String...names)
    {
        LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> premissions = principal.getPremissions();
        if(premissions.contains(MANAGE_MENU))
        {   principal.setJudge(true);
            return true;

        }
        ArrayList<String> blockAuthorityNums = new ArrayList<>();
        Boolean flag=false;
        for (int i = 0; i < names.length; i++)
        {
            String name=names[i];
            int needPreLength = name.length();

            for(int j=0;j<premissions.size();j++)
            {
                String premission = premissions.get(j);
                int havePreLength = premission.length();
               if(havePreLength<needPreLength)
                   continue;
                String realPre=premission.substring(0,needPreLength);
                if(realPre.equals(name))
                {    flag=true;
                    if(needPreLength==havePreLength)
                     principal.setJudge(true);
                    else
                {
                 String preNum=premission.substring(needPreLength+1,havePreLength);

                      blockAuthorityNums.add(preNum);
                }



                }

            }


        }

        principal.setBlockNums(blockAuthorityNums);

        return flag;

    }

    private int getEndInd(String premission)
     {
       int l=  premission.length()-1;
       for(int i=l;i>=0;i--)
       {   char c=premission.charAt(i);
           if(c=='_')
               return i;

       }
     return 0;
     }


}
